package com.jn.zhinongbao.adapter;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.supportingagriculturaltreasures.adapter.MerchantProductAdapter;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MyProductsActivity extends AppCompatActivity implements MerchantProductAdapter.OnProductActionListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout tvEmpty;
    private FloatingActionButton fabAdd;
    
    private MerchantProductAdapter adapter;
    private List<Product> productList;
    
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_products);

        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("我的货品");
        }

        initViews();
        initData();
        setupRecyclerView();
        loadProducts();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recycler_view);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh);
        tvEmpty = findViewById(R.id.tv_empty);
        fabAdd = findViewById(R.id.fab_add);

        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadProducts);
        
        // 添加商品按钮
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(this, PublishProductActivity.class);
            startActivity(intent);
        });
    }

    private void initData() {
        preferenceManager = new PreferenceManager(this);
        databaseHelper = new DatabaseHelper(this);
        productList = new ArrayList<>();
        
        // 获取当前用户
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
        }
    }

    private void setupRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MerchantProductAdapter(productList, this);
        recyclerView.setAdapter(adapter);
    }

    private void loadProducts() {
        if (currentUser == null) {
            Toast.makeText(this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 根据商家ID获取商品
        List<Product> products = databaseHelper.getProductsByMerchantId(currentUser.getId());
        
        productList.clear();
        productList.addAll(products);
        
        if (productList.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        }
        
        adapter.updateProducts(productList);
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadProducts(); // 从其他页面返回时刷新数据
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_products_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_refresh) {
            loadProducts();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onEditProduct(Product product) {
        Intent intent = new Intent(this, EditProductActivity.class);
        intent.putExtra("product_id", product.getId());
        intent.putExtra("product_name", product.getName());
        intent.putExtra("product_price", product.getPrice());
        intent.putExtra("product_location", product.getLocation());
        intent.putExtra("product_contact_phone", product.getContactPhone());
        intent.putExtra("product_image_url", product.getImageUrl());
        intent.putExtra("product_category", product.getCategory());
        startActivity(intent);
    }

    @Override
    public void onDeleteProduct(Product product) {
        new AlertDialog.Builder(this)
                .setTitle("删除商品")
                .setMessage("确定要删除商品「" + product.getName() + "」吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    if (databaseHelper.deleteProduct(product.getId())) {
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        loadProducts();
                    } else {
                        Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onViewProduct(Product product) {
        // 查看商品详情
        Intent intent = new Intent(this, ProductDetailActivity.class);
        intent.putExtra("product_id", product.getId());
        intent.putExtra("product_name", product.getName());
        intent.putExtra("product_price", product.getPrice());
        intent.putExtra("product_location", product.getLocation());
        intent.putExtra("product_contact_phone", product.getContactPhone());
        intent.putExtra("product_image_url", product.getImageUrl());
        intent.putExtra("product_category", product.getCategory());
        intent.putExtra("product_shop_name", product.getShopName());
        intent.putExtra("product_merchant_name", product.getMerchantName());
        intent.putExtra("product_merchant_id", product.getMerchantId());
        intent.putExtra("product_likes", product.getLikes());
        startActivity(intent);
    }
} 